package 生产者和消费者模型;

import java.util.Random;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;

public class Task {

    private static LinkedBlockingDeque<Integer> queue = new LinkedBlockingDeque<>(10);

    //原子类
    private static AtomicInteger value = new AtomicInteger(0);

    private static boolean isFinished = false;

    public static void main(String[] args) {

        Thread producerThread1 = new Thread(new Producer("生产者1"));
        Thread producerThread2 = new Thread(new Producer("生产者2"));
        Thread producerThread3 = new Thread(new Producer("生产者3"));
        Thread consumerThread1 = new Thread(new Consumer("消费者1"));
        Thread consumerThread2 = new Thread(new Consumer("消费者2"));

        producerThread1.start();
        producerThread2.start();
        producerThread3.start();

        consumerThread1.start();
        consumerThread2.start();
    }

    static class Producer implements Runnable {
        private String name;

        public Producer(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            for (int i = 0; i < 8; i++) {
                try {
                    Thread.sleep(300); // 模拟生产时间
                    int x = value.incrementAndGet();
                    queue.put(x);
                    System.out.println(name + " 生产了 " + x + "，当前队列大小：" + queue.size());
                    isFinished = true;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Consumer implements Runnable {

        private String name;

        public Consumer(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    if (queue.isEmpty() && isFinished) {
                        System.out.println("结束");
                        break;
                    }
                    Thread.sleep(500); // 模拟消费时间
                    int consumedValue = queue.take(); // 从队列中取出值进行消费
                    System.out.println(name + " 消费了 " + consumedValue + "，当前队列大小：" + queue.size());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


